import { DateRangeSelector } from '@/components/date-range-selector';
import { DATE_FOMRAT } from '@/constants';
import { DetailResult, WeiXinUser } from '@/pages/types/type';
import { getRequestInit, urlPrefix } from '@/utils/http';
import { DatePicker, Picker } from 'antd-mobile';
import { DownOutline } from 'antd-mobile-icons';
import { PickerValue } from 'antd-mobile/es/components/picker-view';
import * as echarts from 'echarts';
import React, { useEffect, useRef, useState } from 'react';
import styles from '../index.less';
const dayjs = require('dayjs');
require('dayjs/plugin/quarterOfYear');
dayjs.extend(require('dayjs/plugin/quarterOfYear'));

interface SalesPersonStatistics {
  leader: WeiXinUser;
  opportunity: number;
  signed: number;
  paid: number;
  yearMonth: string;
}

export default ({ period }: { period: string }) => {
  const chartRef = useRef(null);
  const [paids, setPaids] = useState<SalesPersonStatistics[]>([]);
  const [range, setRange] = useState<string[]>([]);

  async function getPaidList() {
    fetch(
      `${urlPrefix}/api/block/paid-statistics/${range[0]}/${range[1]}`,
      getRequestInit(),
    )
      .then((rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(({ data, code }: DetailResult<SalesPersonStatistics[]>) => {
              if (code === 0) {
                setPaids(data!);
              }
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
      });
  }

  useEffect(() => {
    if (range.length === 2) {
      getPaidList();
    }
  }, [range]);

  // echarts图表绘制
  useEffect(() => {
    if (!chartRef.current) {
      return;
    }
    const chart = echarts.init(chartRef.current);
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: 15,
        right: 15,
        bottom: 0,
        top: 50,
        containLabel: true,
      },
      legend: {
        data: ['商机', '新签', '收款'],
      },
      xAxis: [
        {
          type: 'category',
          data: paids.flatMap((p) => p.leader.name),
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: '商机',
          type: 'bar',
          data: paids.flatMap((p) => p.opportunity / 10000),
        },
        {
          name: '新签',
          type: 'bar',
          data: paids.flatMap((p) => p.signed / 10000),
        },
        {
          name: '收款',
          type: 'bar',
          data: paids.flatMap((p) => p.paid / 10000),
        },
      ],
    };

    chart.setOption(option);

    // 注意：这里需要返回一个清理函数，以确保在组件卸载时销毁ECharts实例
    return () => {
      chart.dispose();
    };
  }, [chartRef.current, paids]);

  return (
    <>
      <div className={styles.chartGroup}>
        <div className={styles.select}>
          <DateRangeSelector
            period={period}
            onTimeChange={(a, b,type) => setRange([a, b])}
          />
        </div>
        <div className={styles.chart} ref={chartRef}></div>
      </div>
    </>
  );
};
